package cn.edu.gzist.chapter08kafka.kafkaclient;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class KafkaProducerMain {
    public static void main(String[] args) {
        // 1. 配置 Kafka 连接、反序列化、消费者组等参数
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); // Kafka 集群地址 bootstrap.servers
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); // 键的序列化器 "key.serializer", "org.apache.kafka.common.serialization.StringSerializer"
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,StringSerializer.class.getName()); // 值的序列化器 "value.serializer", "org.apache.kafka.common.serialization.StringSerializer"

        // 2. 创建 Producer 实例
        Producer<String, String> producer;
        producer = new KafkaProducer<>(props);

        // 3. 构造消息（指定主题、键、值）
        String topic = "test_topic"; // 要发送到的主题，需提前在 Kafka 创建或允许自动创建
        String key = "key1";
        String value = "Hello, Kafka from IDEA!";
        ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, value);

        // 4. 发送消息（异步发送 + 回调处理结果）
        producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata metadata, Exception exception) {
                if (exception != null) {
                    System.err.println("消息发送失败：" + exception.getMessage());
                } else {
                    System.out.printf("消息发送成功！主题：%s，分区：%d，偏移量：%d%n",
                            metadata.topic(), metadata.partition(), metadata.offset());
                }
            }
        });

        // 5. 关闭 Producer（实际生产环境可能在程序结束时或合适时机关闭）
        producer.close();

    }
}
